﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;
using iLangl.BusinessModel.DAL;
using iLangl.BusinessModel.Actions;

namespace iLangl.BusinessModel.Managers
{
	public class TranslationProviderManager : BaseManager
	{
		#region Singelton Pattern
		private TranslationProviderManager()
		{
		}

		private static TranslationProviderManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the TranslationProviderManager.
		/// </summary>
		public static TranslationProviderManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new TranslationProviderManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public void SetDefaultTranslationProvider(String providerId)
		{
			DALFacade.Instance.TranslationProviderDAL.SetDefaultTranslationProvider(providerId);
		}

		public void SendProjectToTranslationProvider(String projectId)
		{
			Project project = ProjectManager.Instance.GetProject(projectId);
			String providerId = DALFacade.Instance.TranslationProviderDAL.GetTranslationProviderIdForCompany(project.Owner.Company.Id);

			//Find Plugin License
			PluginLicense license = PluginManager.Instance.GetLicenseByCompanyId(providerId);
			//
			ProjectManager.Instance.ToPluginLanguagesMapping(project, license);

			WorkArea tpworkkarea = WorkAreaManager.Instance.GetTPWorkArea(providerId, project.WorkArea.Id);

			if (tpworkkarea == null)
			{
				//TODO: Change on alert system in future
				throw new ApplicationException(String.Format("Missed mapping data for plugin '{0}' with Id='{1}' and WorkArea with Id ={2}", license.Plugin.Name, license.Plugin.ID, project.WorkArea.Id));
			}

			project.WorkArea = tpworkkarea;

			Product tpproduct = ProductManager.Instance.GetTPProduct(providerId, project.Product.Id);

			if (tpproduct == null)
			{
				//TODO: Change on alert system in future
				throw new ApplicationException(String.Format("Missed mapping data for plugin '{0}' with Id='{1}' and Product with Id ={2}", license.Plugin.Name, license.Plugin.ID, project.Product.Id));
			}

			project.Product = tpproduct;

			OrderProject orderprojectAction = new OrderProject(project);
			ActionManager.Instance.PrepareAction(license, orderprojectAction);
			orderprojectAction.Send();

			ProjectManager.Instance.AddSubscriber(project, license, false);
		}


		public void RegisterTranslationProvider(Company company)
		{
			DALFacade.Instance.TranslationProviderDAL.RegisterTranslationProvider(company, null);
		}
	}
}
